// pages/studyWord/paperCut/paperCut.js
const app = getApp();
const httpUtils = require('../../../utils/httpUtils.js');
let wordlist = [{
  "id": "20061",
  "translate": "饥饿的",
  "word": "hungry"
}, {
  "id": "20072",
  "translate": "阿姨",
  "word": "aunt"
}, {
  "id": "20111",
  "translate": "鸡肉",
  "word": "chicken"
},{
  "id": "20060",
  "translate": "纸张",
  "word": "paper"
}, {
  "id": "20073",
  "translate": "你好",
  "word": "hello"
}, {
  "id": "20111",
  "translate": "鸡肉",
  "word": "chicken"
},
{
  "id": "20060",
  "translate": "纸张",
  "word": "paper"
}, {
  "id": "20078",
  "translate": "最后",
  "word": "last"
}
];

let current = [{
  "id": "20061",
  "translate": "饥饿的",
  "word": "hungry"
},];


Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageName: '剪纸条',
    navH: app.globalData.navHeight,
    windowHeight: 0,
    imageurl: app.globalData.imageurl, //图片的总路径
    audiopath: app.globalData.voicepath, //单词的声音路径
    innerAudioContext: new Object(),
    startX: 0, //开始坐标
    startY: 0,
    wordlist: [], //需先进行剪纸的单词
    yesnum: 0, //会的单词数量
    noNum: 0, //不会的单词的数量
    studyNum: 0, //黄色盒子需学习的单词数量
    isCut: 1, //是否是第一次进入需要剪纸条，iscut 0不需要隐藏，为1显示先剪
    studyList: [], //需学习的单词列表---黄色盒子里面的词
    currentwordList: [], //当前屏幕上的单词列表
    canlist: [], //会的盒子词
    unkownList: [], //不会的红盒子的词
    groupData: [], //混组的数据
    scenceShearData: [], //所有学过的单词（可推纸条学习的词）
    istotalDisabled: true, //黄色格子是否可点，先剪纸条的时候设为true不可点
    flag: true, //混组弹窗的显示标志
    fall_img: true, //是否隐藏掉落的小纸条
    fall_x: 0,
    fall_y: 0,
    fallAnimation: {}, //纸条掉落动画
    hide_img: true, //是否隐藏加入购物车的小纸条
    bus_x: '', //掉落图片的位置
    bus_y: '',
    green_box_pos: {}, //左边会的绿盒子的位置
    red_box_pos: {},  //右边不会的词红盒子的位置
    finger: {}, //手指按下的坐标，也是起点坐标
  
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let green_box_pos = {};
    let red_box_pos = {};
    let finger = {};
    finger['x'] = 0;
    finger['y'] = 0;
    green_box_pos['x'] = app.globalData.ww * 0.1;
    green_box_pos['y'] = app.globalData.hh * 0.95;
    red_box_pos['x'] = app.globalData.ww * 0.75;
    red_box_pos['y'] = app.globalData.hh * 0.95;

    that.setData({
      finger: finger,
      green_box_pos: green_box_pos,
      red_box_pos: red_box_pos,
    })
    let wordlist = that.data.wordlist;
    let studyList = that.data.studyList;
    let scenceShearData = that.data.scenceShearData;
    //获取识记界面传过来的单词
    let currentPage = options.currentPage;
    let studyGroup = options.studyGroup;
    let isCut = options.isCut;
    let istotalDisabled = that.data.istotalDisabled;
    let wordData = JSON.parse(options.groupdata);

    for (var i = 0; i < studyGroup; i++) {
      for (var j = 0; j < wordData[i].length; j++) {
        wordData[i][j].click = 0;
        wordData[i][j].fontw = 400;
        wordData[i][j].isTouchMove = false
      }
      scenceShearData.push(wordData[i]);
    }
    console.log("scenceShearData=" + JSON.stringify(scenceShearData))
    if (isCut == 1) {
      //先剪纸
      wordlist = wordlist.concat(scenceShearData[scenceShearData.length - 1]);
      console.log("wordlist=" + JSON.stringify(wordlist));
      istotalDisabled = true;
    } else {
      //直接推纸条
      istotalDisabled = false;
      if (currentPage > 0 && currentPage <= scenceShearData.length) {
        studyList = studyList.concat(scenceShearData[currentPage - 1])
      } else {
        studyList = studyList.concat(scenceShearData[scenceShearData.length - 1])
      }
      console.log("studyList=" + JSON.stringify(studyList))
    }
    that.setData({
      isCut: isCut,
      istotalDisabled: istotalDisabled,
      scenceShearData: scenceShearData,
      wordlist: wordlist,
      studyList: studyList,
      studyNum: studyList.length
    })

    //初始化audio
    that.data.innerAudioContext = wx.createInnerAudioContext();
    that.data.innerAudioContext.autoplay = false;
    that.data.innerAudioContext.loop = false;

    //更新数据源，添加一些属性
    //第一次剪纸条的
    let temparr = that.data.wordlist; //剪的
    for (let i = 0; i < temparr.length; i++) {
      temparr[i].click = 0;
      temparr[i].fontw = 400;
      temparr[i].isTouchMove = false
    }
    that.setData({
      wordlist: temparr,
    })
    that.initPopMixData();
    //初始化黄盒子的---需学习的词的状态
    that.initStudylistState();
  },

  initPopMixData: function () {
    let that = this;
    let temlist = that.data.scenceShearData;
    let temobj = new Object();
    let groupData = that.data.groupData;
    for (var i = 0; i < temlist.length; i++) {
      temobj = new Object();
      temobj.isCheck = false;
      groupData.push(temobj);
    }

    that.setData({
      groupData: groupData
    })
    console.log("initPopMixData---groupData.length=" + this.data.groupData.length)
    console.log("initPopMixData---groupData=" + JSON.stringify(this.data.groupData))
  },

  /**
   * 点击开始（黄色格子）弹出单词学习
   */
  popWord: function () {
    console.log("每点一次弹出一个单词")
    let that = this;
    let index = 0;
    let studyList = that.data.studyList;
    let currentwordList = that.data.currentwordList;

    if (studyList.length > 0) {
      // let audiosrc = that.data.audiopath + studyList[index].word + ".mp3";
      let audiosrc =studyList[index].project_voice;
      that.playAudio(audiosrc);
      currentwordList.push(studyList[index]);
      studyList.splice(0, 1);
      //更新数据
      that.setData({
        currentwordList: currentwordList,
        studyList: studyList,
        studyNum: studyList.length,
      })

      console.log("currentwordList.length=" + currentwordList.length)
    }


  },


  //点击红色盒子（每次弹一个不会的词）
  showHardWord: function () {
    let that = this;
    let unkownList = that.data.unkownList;
    let currentwordList = that.data.currentwordList;

    if (unkownList.length > 0) {
      // let audiosrc = that.data.audiopath + unkownList[0].word + ".mp3";
      let audiosrc =unkownList[0].project_voice;
      that.playAudio(audiosrc);
      unkownList[0].click = 0;
      unkownList[0].fontw = 400;
      unkownList[0].isTouchMove = false
      currentwordList.push(unkownList[0]);
      unkownList.splice(0, 1);
      that.setData({
        currentwordList: currentwordList,
        unkownList: unkownList,
        noNum: unkownList.length,
      })
    }
  },

  //点击标题栏返回键
  navbarBack: function () {
    let that = this;
    let isCut = this.data.isCut;
    let studyList = this.data.studyList;
    let currentwordList = this.data.currentwordList;
    if (isCut == 1) {
      wx.showToast({
        title: '完成剪纸条才可以退出哦~~',
        icon: 'none'
      })
      return;
    }

    if (studyList.length != 0 || currentwordList.length != 0) {
      wx.showToast({
        title: '您还有未检查完的纸条',
        icon: 'none'
      })
      return;
    }
    if (this.data.unkownList.length != 0) {
      wx.showToast({
        title: '不会的词还没学完哦~',
        icon: 'none'
      })
      return;
    }

    //后期自定义一个mask
    wx.showModal({
      title: '提示',
      content: '确认要返回识记吗？',
      showCancel: true,
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.navigateBack({
            delta: 1
          })
        } else if (res.cancel) {
          console.log('用户点击取消')

        }

      }
    })

  },

  //再检查一遍
  studyAgain: function () {
    let that = this;
    let studyList = this.data.studyList;
    let currentwordList = this.data.currentwordList;
    let canlist = this.data.canlist;
    let unkownList = this.data.unkownList;
    if (studyList.length != 0 || currentwordList.length != 0) {
      wx.showToast({
        title: '您还有未检查完的纸条',
        icon: 'none'
      })
      return;
    }

    if (unkownList.length != 0) {
      wx.showToast({
        title: '不会的词还没学完哦',
        icon: 'none'
      })
      return;
    }
    if (canlist.length != 0) {
      //再来一遍的动画和音效
      that.playAudio(app.globalData.mp3.wordin);

      //动画结束后
      let disorderArray = [];
      disorderArray = that.disorderArray(canlist);
      that.setData({
        canlist: [],
        yesnum: 0,
      })
      for (let i = 0; i < disorderArray.length; i++) {
        studyList.push(disorderArray[i])
      }
      // studyList.concat(canlist);
   
      that.setData({
        studyList: studyList,
        yesnum: 0,
        studyNum: studyList.length,
        canlist: [],
      })
      console.log("yesnum:" + that.data.yesnum)
      that.initStudylistState();

    } else {
      wx.showToast({
        title: '先学难词，或者继续识记吧',
        icon: 'none'
      })
    }

  },

  // 数组乱序
  disorderArray(arr) {
    for (let i = 0; i <= arr.length - 1; i++) {
      let randomIndex = Math.round(Math.random() * i)
      let temp = arr[randomIndex]
      arr[randomIndex] = arr[i]
      arr[i] = temp
    }
    return arr
  },

  //混组检查
  mixCheck: function () {
    let that = this;
    let studyList = this.data.studyList;
    let currentwordList = this.data.currentwordList;
    let unkownList = this.data.unkownList;
    let groupData = that.data.groupData;

    if (studyList.length != 0 || currentwordList.length != 0) {
      wx.showToast({
        title: '您还有未检查完的纸条',
        icon: 'none'
      })
      return;
    }

    if (unkownList.length != 0) {
      wx.showToast({
        title: '不会的词还没学完哦',
        icon: 'none'
      })
      return;
    }
    if (groupData.length < 2) {
      wx.showToast({
        title: '只学了一组单词，没有其他单词可以混合哦~',
        icon: 'none'
      })
      return;
    }
    // 弹选择混合的窗 showPop();
    that.setData({
      flag: false
    })
  },

  //点击弹窗里在盒子
  clickMixbox: function (e) {
    console.log("clickbox" + JSON.stringify(e))
    let that = this;
    let index = e.currentTarget.dataset.index;
    let groupData = that.data.groupData;
    console.log("点击了盒子" + index);
    console.log("clickMixbox--groupData" + JSON.stringify(groupData))
    if (index < 0 || index >= groupData.length) {
      return;
    }
    groupData[index].isCheck = groupData[index].isCheck ? false : true;
    that.setData({
      groupData: groupData
    })
  },

  //点击弹窗的开始检测按钮
  beginMixCheck: function () {
    let that = this;
    let studyList = that.data.studyList;
    let groupData = that.data.groupData;
    let scenceShearData = that.data.scenceShearData;
    console.log("beginMixCheck---groupData:" + JSON.stringify(groupData));
    console.log("beginMixCheck---scenceShearData" + JSON.stringify(scenceShearData));
    studyList = [];
    for (var i = 0; i < groupData.length; i++) {
      if (groupData[i].isCheck) {
        for (var j = 0; j < scenceShearData[i].length; j++) {
          scenceShearData[i][j].click = 0;
          scenceShearData[i][j].fontw = 400;
          scenceShearData[i][j].isTouchMove = false
          studyList.push(scenceShearData[i][j]);
        }
      }
    }
    console.log("studyList.length=" + studyList.length)
    studyList=that.disorderArray(studyList);
    console.log("studyList:" + JSON.stringify(studyList))
    that.setData({
      studyList: studyList,
      unkownList: [],
      canlist: [],
      studyNum: studyList.length,
      yesnum: 0,
      noNum: 0,
      flag: true
    })
  },

  // 关闭弹窗
  closeMask: function () {
    this.setData({
      flag: true
    })
  },

  //初始化黄盒子的---需学习的词的状态
  initStudylistState: function () {
    let that = this;
    let templist = that.data.studyList; //推纸条学习的
    templist=that.disorderArray(templist);
    for (let i = 0; i < templist.length; i++) {
      templist[i].click = 0;
      templist[i].fontw = 400;
      templist[i].isTouchMove = false
    }
    that.setData({
      studyList: templist
    })
  },

  //点击推纸条学习的单词条目
  clickWordItem: function (e) {
    let that = this;
    let idx = e.currentTarget.dataset.index;
    let word = e.currentTarget.dataset.word;
    let tmp = new Object;
    tmp = that.data.currentwordList;
    // let audiosrc = that.data.audiopath + word + ".mp3";
    let audiosrc=e.currentTarget.dataset.audios;
    that.playAudio(audiosrc);
    for (var i = 0; i < tmp.length; i++) {
      if (i == idx) {
        console.log("点击了", idx)
        tmp[idx].fontw = 800;
        if (tmp[idx].click < 2) {
          tmp[idx].click = parseInt(tmp[idx].click) + 1;
        } else {
          tmp[idx].click = 1;
        }
        console.log("tmp[idx].click:", tmp[idx].click)
      } else {
        tmp[i].click = 0;
        tmp[i].fontw = 400;
      }
    }
    //更新数据
    that.setData({
      currentwordList: tmp,
    })

  },

  //推纸条学习时-手指触摸动作开始 记录起点X坐标
  touchitemstart: function (e) {
    //开始触摸时，重置所有操作项
    let that = this;
    let idx = e.currentTarget.dataset.index;
    let temlist = that.data.currentwordList;
    temlist.forEach(function (v, i) {
      if (v.isTouchMove) { //只操作为true的
        v.isTouchMove = false;
      }
    })

    that.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      currentwordList: temlist
    })
  },

  //推纸条学习时---手指滑动
  touchitemmove: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.index; //当前索引
    let temlist = that.data.currentwordList; //当前屏幕推纸条学习的list
    let startX = that.data.startX;
    let startY = that.data.startY;
    let touchMoveX = e.changedTouches[0].clientX; //滑动变化坐标
    let touchMoveY = e.changedTouches[0].clientY; //滑动变化坐标
    let angle = that.angle({
      X: startX,
      Y: startY
    }, {
      X: touchMoveX,
      Y: touchMoveY
    }); //获取角度

    temlist.forEach(function (v, i) {
      v.isTouchMove = false;
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i === index) {
        if (touchMoveX > startX) { //右滑
          v.isTouchMove = true;
        } else { //左滑
          v.isTouchMove = true;
        }
      }
    })

    //更新数据
    that.setData({
      currentwordList: temlist
    })
  },
  // 推纸条学习时手指触摸结束
  touchitemend: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.index; //当前索引
    let temlist = that.data.currentwordList; //当前屏幕推纸条学习的list
    let studyList = that.data.studyList; //需学习的词--黄色盒子的词
    let canlist = that.data.canlist; //会的盒子词
    let unkownList = that.data.unkownList; //不会的红盒子的词
    let startX = that.data.startX;
    let startY = that.data.startY;
    let touchMoveX = e.changedTouches[0].clientX; //滑动变化坐标
    let touchMoveY = e.changedTouches[0].clientY; //滑动变化坐标
    let angle = that.angle({
      X: startX,
      Y: startY
    }, {
      X: touchMoveX,
      Y: touchMoveY
    }); //获取角度

    temlist.forEach(function (v, i) {
      if (i == index & v.isTouchMove) {
        console.log("i==index,滑动了", index)
        // 起点
        let finger = that.data.finger;
        finger['x'] = app.globalData.ww / 2;
        finger['y'] = startY;
        that.setData({
          finger: finger,
        })
        let isLeft;
        // 滑动后 若左滑 会的盒子添加该元素,右滑不会的盒子添加该元素,最后学习list移除该元素,学习数-1，
        if (touchMoveX > startX) { //右滑
          isLeft = false;
          console.log("右滑了，执行个掉落动画，加入不会的红色盒子")
          unkownList.push(temlist[index]);
          temlist.splice(index, 1);
          that.setData({
            noNum: unkownList.length,
            studyList: studyList,
            currentwordList: temlist,
            unkownList: unkownList,
            studyNum: studyList.length,
          })

          //执行下落动画
          if (!that.data.hide_img) {
            return;
          }
          let redboxPos = that.data.red_box_pos;
          var topPoint = {};
          // topPoint['x'] = Math.abs(finger['x'] - redboxPos['x']) / 2 + finger['x'];
          // topPoint['y'] = redboxPos['y'] - 130;
          topPoint['x'] = redboxPos['x'];
          topPoint['y'] = finger['y'];

          that.startAnimation(finger, topPoint, redboxPos);
          //落入的声音
          that.playAudio(app.globalData.mp3.wordin);
        } else { //左滑
          isLeft = true;
          console.log("左滑了，执行个掉落动画，加入会的yes绿盒子")
          canlist.push(temlist[index]);
          temlist.splice(index, 1);
          that.setData({
            studyList: studyList,
            currentwordList: temlist,
            canlist: canlist,
            studyNum: studyList.length,
            yesnum: canlist.length,
          })

          //执行下落动画
          if (!that.data.hide_img) {
            return;
          }
          //终点
          let greenboxPos = that.data.green_box_pos;
          //控制点
          var topPoint = {};
          topPoint['x'] = greenboxPos['x'];
          topPoint['y'] = finger['y'];

          that.startAnimation(finger, topPoint, greenboxPos, isLeft);
          //播放音效
          that.playAudio(app.globalData.mp3.wordin);
        }

      }
    })

  },

  // 小纸条加入购物车的二次贝塞尔曲线动画
  startAnimation: function (fingerpos, topPoint, boxPos, isLeft) {
    let index = 0;
    let that = this;
    let finger = this.data.finger;
    let linePos = app.bezier([fingerpos, topPoint, boxPos], 30, isLeft);
    let bezier_points = linePos['bezier_points'];

    that.setData({
      hide_img: false,
      bus_x: finger['x'],
      bus_y: finger['y']
    })

    this.timer = setInterval(function () {
      index++;
      that.setData({
        bus_x: bezier_points[index]['x'],
        bus_y: bezier_points[index]['y']
      })
      if (index >= 28) {
        clearInterval(that.timer);
        that.setData({
          hide_img: true,
        })
      }
    }, 30);
  },


  //点击剪纸条的单词条目
  clickWord: function (e) {
    let that = this;
    let idx = e.currentTarget.dataset.index;
    let word = e.currentTarget.dataset.word;
    let tmp = new Object;
    tmp = that.data.wordlist;
    // let audiosrc = that.data.audiopath + word + ".mp3";
    let audiosrc=e.currentTarget.dataset.audios;
    that.playAudio(audiosrc);
    for (var i = 0; i < tmp.length; i++) {
      if (i == idx) {
        console.log("点击了", idx)
        tmp[idx].fontw = 1000;
        if (tmp[idx].click < 2) {
          tmp[idx].click = parseInt(tmp[idx].click) + 1;
        } else {
          tmp[idx].click = 1;
        }
        console.log("tmp[idx].click:", tmp[idx].click)
      } else {
        tmp[i].click = 0;
        tmp[i].fontw = 400;
      }
    }
    //更新数据
    that.setData({
      wordlist: tmp,
    })

  },

  //手指触摸动作开始 记录起点X坐标
  touchstart: function (e) {
    //开始触摸时，重置所有操作项
    let that = this;
    let idx = e.currentTarget.dataset.index;
    let temlist = that.data.wordlist;
    console.log("idx:", idx);
    console.log(e)
    temlist.forEach(function (v, i) {
      if (v.isTouchMove) { //只操作为true的
        v.isTouchMove = false;
      }
    })

    that.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      wordlist: temlist
    })
  },

  //滑动事件处理--触摸时触发，手指在屏幕上每移动一次，触发一次
  touchmove: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.index; //当前索引
    let temlist = that.data.wordlist; //需剪纸条的list
    let studyList = that.data.studyList;
    let studyNum = that.data.studyNum;
    let startX = that.data.startX;
    let startY = that.data.startY;
    let touchMoveX = e.changedTouches[0].clientX; //滑动变化坐标
    let touchMoveY = e.changedTouches[0].clientY; //滑动变化坐标
    let angle = that.angle({
      X: startX,
      Y: startY
    }, {
      X: touchMoveX,
      Y: touchMoveY
    }); //获取角度

    temlist.forEach(function (v, i) {
      v.isTouchMove = false;
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i === index) {
        if (touchMoveX > startX) { //右滑
          v.isTouchMove = true;
        } else { //左滑
          v.isTouchMove = true;
        }

      }
    })

    //更新数据
    that.setData({
      wordlist: temlist
    })
  },

  touchend: function (e) {
    console.log("touchend" + e)
    let that = this;
    let index = e.currentTarget.dataset.index; //当前索引
    let startX = that.data.startX;
    let startY = that.data.startY;
    let temlist = that.data.wordlist; //需剪纸条的list
    let studyList = that.data.studyList;

    temlist.forEach(function (v, i) {
      if (i === index & v.isTouchMove) {
        console.log("i==index,滑动了", index)
        //剪纸动画
        that.setData({
          fall_x: app.globalData.ww*0.45,
          fall_y: startY,
          fall_img: false
        })
        that.startFallAnim();
 
        //播单词掉入盒子的声音
        that.playAudio(app.globalData.mp3.wordin);
        // 滑动后 学习数+1，学习list先添加该元素，然后temlist移除该元素
        studyList.push(temlist[index]);
        temlist.splice(index, 1);
        that.setData({
          studyNum: studyList.length,
          studyList: studyList,
          wordlist: temlist
        })
      }
    })

    if (that.data.wordlist.length == 0) {
      //剪完纸条了
      that.initStudylistState();
      that.setData({
        isCut: 0,
        istotalDisabled: false,
        studyNum: that.data.studyList.length
      })
    }

  },

  startFallAnim: function () {
    let that=this;
    setTimeout(function () {
      that.setData({
        fall_img: true,
      })
    }, 1000)
  },
   

  /**  
   * 计算滑动角度 
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值 
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },

  /**播放声音 */
  playAudio: function (audiosrc) {
    this.data.innerAudioContext.stop();
    this.data.innerAudioContext.src = audiosrc;
    this.data.innerAudioContext.play();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
 
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})